/**
 * 图片上传管理
 */

/*
 * HTML CODE

 必须依赖：

 {#相关脚本#}
 <link rel="stylesheet" href="{{ root }}/ac/css/0zPic.css{{ rnd }}">
 <script src="{{ root }}/ac/js/0zPic.js{{ rnd }}"></script>


非必须依赖，图片上传到OSS时使用，to oss = 1
 <script type="text/javascript" src="{{ root }}/assets/oss/lib/crypto1/crypto/crypto.js{{ rnd }}"></script>
 <script type="text/javascript" src="{{ root }}/assets/oss/lib/crypto1/hmac/hmac.js{{ rnd }}"></script>
 <script type="text/javascript" src="{{ root }}/assets/oss/lib/crypto1/sha1/sha1.js{{ rnd }}"></script>
 <script type="text/javascript" src="{{ root }}/assets/oss/lib/base64.js{{ rnd }}"></script>
 <script type="text/javascript" src="{{ root }}/assets/oss/uploadMy.js{{ rnd }}"></script>


 头像：
 <!-- 头像管理  start-->
 <div id="UserHead">
 <div  class="MultiPicManager flex-r bdtdo padt10">
 <div class="MultiPicList flex flex-center" data-bind="for:viewData">
 <div class="MultiPicListItem c13 round10 bdso flex-center mar10"
 data-data="0" data-bind="attr:{'data-data':value}">
 {#<span class="MultiPicListItemDel fa fa-times-circle"></span>#}
 <img class="" src="" data-bind="attr:{src:value}" />
 </div>
 </div>
 </div>
 <div id="" class="">
 <div class="HeadPicAdd c13 bdso bdc13 flex-center mar10 pad10">修改</div>
 </div>
 <div class="MultiPicData hidden" data-bind="for:inputData">
 <input name="addPics[]" value="" type="hidden" data-bind="attr:{value:value}" />
 </div>
 </div>


 多图：
 <!-- 多图管理  start-->
 <div id="addPics" class="MultiPicManager flex-r bdtdo padt10">
 <div class="MultiPicList flex-r" data-bind="for:viewData">
 <div class="MultiPicListItem c13 round10 bdso flex-center mar10"
 data-data="0" data-bind="attr:{'data-data':value}">
 <span class="MultiPicListItemDel fa fa-times-circle"></span>
 <img class="" src="" data-bind="attr:{src:value}" />
 </div>
 </div>
 <div id="" class="">
 <div class="MultiPicAdd fs60 c13 bdso bdc13 flex-center mar10">+</div>
 </div>
 <div class="MultiPicData hidden" data-bind="for:inputData">
 <input name="addPics[]" value="" type="hidden" data-bind="attr:{value:value}" />
 </div>
 </div>

JS CODE
//多图
 InitMultiPic("#addPics",function(){
 log(MultiPicGetPic("addPics"))
 log(MultiPicGetPics("addPics"))
 },9,0.2);

 //编辑
 InitEditPic("#EditPic",function(){
 log(MultiPicGetPic("EditPic"))
 log(MultiPicGetPics("EditPic"))
 },0.1);

//头像
 InitHeadEditor("#UserHead",function(){
 log(MultiPicGetPic("UserHead"))
 log(MultiPicGetPics("UserHead"))
 },0.1);

 * */



//考虑到页面内可以有多个使用数组对象结构
//var MultiPicMainBoxSelector = {};
var MultiPicLocalPath       = {};
var MultiPicInputData       = {};
var MultiPicViewData        = {};

//上传完成后获取图片的方法
function MultiPicGetPic(uniqueName){return MultiPicInputData[uniqueName][0]}
function MultiPicGetPics(uniqueName){return MultiPicInputData[uniqueName]}

function InitMultiPic (selector,callBackFunc,maxNum,quality) {
    if(maxNum == undefined) maxNum = 9;
    if(maxNum == undefined) maxNum = 0.3;
    ontap(selector + " .MultiPicAdd",function () {
        uexImage.openPicker({max:maxNum,quality:quality},function(error,info){
            if(error==-1){
                log("cancelled!");
            }else if(error==0) {
                var path = info.data;
                //图片上传方法,path为数组；
                log(path)
                zPicUploadLocalPic(path,selector,callBackFunc)
                return false;
            }
        });
    })
    //删除事件绑定
    zPicBindDel(selector)
    //初始化数据
    zPicInitEmptyData(selector)
}

//拾取图片后可以编辑
function InitEditPic (selector,callBackFunc,quality) {
    if(quality == undefined) quality = 0.3;
    ontap(selector + " .MultiPicAdd",function () {
        appcan.window.actionSheet({
            title:"请选择操作",
            cancelText:"取消",
            buttons:["拍照","从相册选择"],
            callback:function(err,data){
                if(!err)logJson(data)
                switch(data){
                    case 0://拍照
                        zPicEditCamera(function (picPath) {
                            var path = [];
                            path[0] = picPath;
                            //图片上传方法,path为数组；
                            zPicUploadLocalPic(path,selector,callBackFunc)
                            return false;
                        })
                        break;
                    case 1://从相册选择
                        zPicEditAlbumOne(quality,function (picPath) {
                            var path = [];
                            path[0] = picPath;
                            //图片上传方法,path为数组；
                            zPicUploadLocalPic(path,selector,callBackFunc)
                            return false;
                        })
                        break;
                    default:
                }
            }
        });
    })
    //删除事件绑定
    zPicBindDel(selector)
    //初始化数据
    zPicInitEmptyData(selector)
}
//拾取图片后可以编辑
function InitHeadEditor (selector,callBackFunc,quality) {
    try{
        if(quality == undefined) quality = 0.3;
        ontap(selector + " .HeadPicAdd",function () {
            appcan.window.actionSheet({
                title:"请选择操作",
                cancelText:"取消",
                buttons:["拍照","从相册选择"],
                callback:function(err,data){
                    if(!err)logJson(data)
                    var uniqueName = selector.substring(1);
                    switch(data){
                        case 0://拍照
                            zPicEditCamera(function (picPath) {
                                //上传前需要清空数据
                                MultiPicViewData[uniqueName] = []
                                MultiPicInputData[uniqueName] = []

                                var path = [];
                                path[0] = picPath;
                                //图片上传方法,path为数组；
                                zPicUploadLocalPic(path,selector,callBackFunc)
                                return false;
                            })
                            break;
                        case 1://从相册选择
                            zPicEditAlbumOne(quality,function (picPath) {
                                //上传前需要清空数据
                                MultiPicViewData[uniqueName] = []
                                MultiPicInputData[uniqueName] = []

                                var path = [];
                                path[0] = picPath;
                                //图片上传方法,path为数组；
                                zPicUploadLocalPic(path,selector,callBackFunc)
                                return false;
                            })
                            break;
                        default:
                    }
                }
            });
        })
    }catch (e){log(e.message)}finally{}
    //删除事件绑定
    //zPicBindDel(selector)
    //初始化数据
    zPicInitEmptyData(selector)
}

function zPicEditCamera (cbFunc) {
    var comtextareass = 0;
    var quality = 50;
    uexCamera.open(comtextareass, quality, function(picPath) {
        var data={
            src:picPath,
            mode:6
        }
        uexImage.openCropper(data,function(error,info){
            if(error==-1){
                alert("cancelled!");
            }else if(error==0) {
                // alert(info.data);
                cbFunc(info.data)
            }
        });
    });
}

function zPicEditAlbumOne (quality,cbFunc) {
    log("zPicEditAlbumOne")
    try{

        uexImage.openPicker({max:1,quality:quality},function(error,info){

            log("this is files you get")
            //logJson(info)
            //logJson(error);
            //logJson(info);
            //if(error==-1){
            //    //
            //    log("cancelled!");
            //}else if(error==0) {
            //    var path = info.data;
            //    var picPath = path[0];
            //    var data={
            //        src:picPath,
            //        mode:6
            //    }
            //    uexImage.openCropper(data,function(error,info){
            //        if(error==-1){
            //            alert("cancelled!");
            //        }else if(error==0) {
            //            // alert(info.data);
            //            cbFunc(info.data)
            //        }
            //    });
            //}
        })
    }catch (e){
        alert(e.message)
    }finally{

        log("zPicEditAlbumOne end")
    }
}

function zPicUploadLocalPic(path,selector,callBackFunc){
    var uniqueName = selector.substring(1);
    if(typeof MultiPicLocalPath[uniqueName] == "undefined"){MultiPicLocalPath[uniqueName] = []}
    MultiPicLocalPath[uniqueName].concat(path);//添加到当前的数据中
    var tmpMultiPicViewData = [];
    var tmpData = [];
    var totalPic = path.length;
    var finished = 0;
    log("zPicUploadLocalPic")
    path.map(function (data,index) {
        tmpMultiPicViewData[index] = data;
        tmpData[index]     = data;
        uploadOnePic(data ,function (res) {
            try{//为保证代码的完整性加入try这里具体有什么错误暂时不清楚
                var pic = res.d;
                var picView = res.d;
                tmpMultiPicViewData[index]  = res.d
                tmpData[index]      = res.d
                finished++
                showToast("上传进度" + finished + "/" + totalPic)
                if(finished == totalPic){
                    if(typeof MultiPicViewData[uniqueName] == "undefined"){MultiPicViewData[uniqueName] = []}
                    if(typeof MultiPicInputData[uniqueName] == "undefined"){MultiPicInputData[uniqueName] = []}
                    tmpMultiPicViewData.map(function (data) {MultiPicViewData[uniqueName].push(data)})
                    tmpData.map(function (data) {MultiPicInputData[uniqueName].push(data)})
                    //showToast("上传成功")
                    log("tmpMultiPicViewData")
                    log(tmpMultiPicViewData)
                    log("tmpData")
                    log(tmpData)
                    viewData[uniqueName] = {inputData:[],viewData:[]}
                    svd(uniqueName)
                    viewData[uniqueName] = {
                        inputData:MultiPicInputData[uniqueName],
                        viewData:MultiPicViewData[uniqueName]
                    }
                    svd(uniqueName)
                    callBackFunc()
                }
            }catch(e){
                log(e.message)
            }finally{}
        })
    })
}

function zPicBindDel(selector){

    var uniqueName = selector.substring(1);
    $(document).on("click",selector + " .MultiPicListItemDel",function(){
        var value = $(this).parent().attr("data-data");
        var value_dataInput = value.substr(baseUrl.length)
        MultiPicViewData[uniqueName] = arrayDelValue(MultiPicViewData[uniqueName],value)
        MultiPicInputData[uniqueName] = arrayDelValue(MultiPicInputData[uniqueName],value_dataInput)
        viewData[uniqueName] = {
            inputData:MultiPicInputData[uniqueName],
            viewData:MultiPicViewData[uniqueName]
        }
        svd(uniqueName)
    })
}
function zPicInitEmptyData(selector){
    var uniqueName = selector.substring(1);
    viewData[uniqueName] = {inputData:[],viewData:[]}
    svd(uniqueName)
}
function zPicInitData(uniqueName,view,input){
    if (typeof  view == "string") {
        viewData[uniqueName] = {inputData:[view],viewData:[input]}

        if(typeof MultiPicViewData[uniqueName] == "undefined"){MultiPicViewData[uniqueName] = [view]}
        if(typeof MultiPicInputData[uniqueName] == "undefined"){MultiPicInputData[uniqueName] = [input]}
    }else{
        if(typeof MultiPicViewData[uniqueName] == "undefined"){MultiPicViewData[uniqueName] = view}
        if(typeof MultiPicInputData[uniqueName] == "undefined"){MultiPicInputData[uniqueName] = input}
        viewData[uniqueName] = {inputData:view,viewData:input}
    }
    svd(uniqueName)

    //删除事件绑定
    //zPicBindDel("#" + uniqueName)
}
